package com.m3839.sdk.pay.model;

import com.m3839.sdk.common.GlobalManager;
import com.m3839.sdk.common.core.ApiError;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.core.SdkConfiguration;
import com.m3839.sdk.common.env.EnvConfig;
import com.m3839.sdk.common.env2.ApiManager;
import com.m3839.sdk.common.event.SubjectBus;
import com.m3839.sdk.common.http.IHttpManager;
import com.m3839.sdk.common.http.listener.DefaultHttpRequestListener;
import com.m3839.sdk.common.http.listener.SimpleHttpRequestListener;
import com.m3839.sdk.common.util.DateUtils;
import com.m3839.sdk.login.bean.InternalUser;
import com.m3839.sdk.login.core.LoginManager;
import com.m3839.sdk.login.utils.UserUtils;
import com.m3839.sdk.pay.bean.OrderInfo;
import com.m3839.sdk.pay.bean.PayConfig;
import com.m3839.sdk.pay.bean.PayLimit;
import com.m3839.sdk.pay.constant.PayConstant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ChenBaoyang
 * @description: PayApiModel
 * @date 2021/12/8 19:29
 */
public class PayApiModel implements IPayModel{


    private static final String PAY_CONFIG_PATH = "pay/config";

    private static final String PAY_SUBMIT_PATH = "pay/submit";

    private static final String PAY_ORDER_QUERY = "pay/search";

    private static final String PAY_NOTIFY_PATH = "pay/notify";

    /**
     * 支付配置接口
     */
    private static final String BASE_PAY_CONFIG_URL
            = ApiManager.getInstance().buildYuanChuangUrl(PAY_CONFIG_PATH);

    /**
     * 支付下单接口
     */
    private static final String BASE_PAY_SUBMIT_URL
            = ApiManager.getInstance().buildYuanChuangUrl(PAY_SUBMIT_PATH);

    /**
     * 订单查询接口
     */
    private static final String BASE_ORDER_QUERY_URL
            = ApiManager.getInstance().buildYuanChuangUrl(PAY_ORDER_QUERY);

    /**
     * 支付信息上报
     */
    private static final String BASE_PAY_NOTIFY_URL
            = ApiManager.getInstance().buildYuanChuangUrl(PAY_NOTIFY_PATH);

    /**
     * 游戏方上报商品发放通知
     */
    private static final String BASE_NOTIFY_GOODS_URL = "http://sdk.3839app.com/pay/log";

    @Override
    public void loadPayConfig() {
        InternalUser user = LoginManager.getInstance().getInternalUser();
        Map<String, Object> param = ApiManager.getInstance()
                .getCommonParam(user.getUserId(), PAY_CONFIG_PATH);
        IHttpManager httpManager = GlobalManager.getInstance().getHttpManager();
        EnvConfig config = ApiManager.getInstance().getYuanChuangApiEnvConfig();

        httpManager.requestPost(BASE_PAY_CONFIG_URL, param,
                ApiManager.getInstance().getAuthHeaders(config, UserUtils.getState(user)),
                new SimpleHttpRequestListener() {

                    @Override
                    public void onResult(String response) throws JSONException {
                        parsePayConfigJson(response);
                    }

                    @Override
                    public void onError(ApiError apiError) {
                        SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_CONFIG_FAILED, apiError);
                    }
                });
    }

    /**
     * 解析用户校验的结果
     *
     * @param response
     * @throws JSONException
     */
    private static void parsePayConfigJson(String response)
            throws JSONException {
        JSONObject data = new JSONObject(response);

        int code = data.optInt(Constant.HYKB_KEY_RESPONSE_CODE);
        String msg = data.optString(Constant.HYKB_KEY_RESPONSE_MSG);
        JSONObject dataJson = data.optJSONObject(Constant.HYKB_KEY_RESPONSE_DATA);

        if (code == Constant.HYKB_CODE_SUCCESS) {
            PayConfig config = new PayConfig().parseBean(dataJson);
            SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_CONFIG, config);
        } else if (code == Constant.HYKB_CODE_PAY_MAINTENANCE) {
            String maintenanceContent = dataJson.optString(
                    Constant.HYKB_KEY_RESPONSE_PAY_MAINTENANCE);
            ApiError apiError = new ApiError(code, maintenanceContent);
            SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_CONFIG_FAILED, apiError);
        } else {
            ApiError apiError = new ApiError(code, msg);
            SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_CONFIG_FAILED, apiError);
        }
    }

    @Override
    public void submitOrder(String cpOrderId, String userName, int money, String goodsName, int server, String ext, String payType) {
        InternalUser user = LoginManager.getInstance().getInternalUser();
        Map<String, Object> param = ApiManager.getInstance()
                .getCommonParam(user.getUserId(), PAY_SUBMIT_PATH);
        IHttpManager httpManager = GlobalManager.getInstance().getHttpManager();
        EnvConfig config = ApiManager.getInstance().getYuanChuangApiEnvConfig();

        param.put(Constant.HYKB_KEY_PAY_GAME_ORDER, cpOrderId);
        param.put(Constant.HYKB_KEY_PAY_MONEY, money);
        param.put(Constant.HYKB_KEY_PAY_USER_NAME, userName);
        param.put(Constant.HYKB_KEY_PAY_GAME_SERVER, server);
        param.put(Constant.HYKB_KEY_PAY_GOODS_NAME, goodsName);
        param.put(Constant.HYKB_KEY_PAY_TYPE, payType);
        param.put(Constant.HYKB_KEY_PAY_EXT, ext);

        httpManager.requestPost(BASE_PAY_SUBMIT_URL, param,
                ApiManager.getInstance().getAuthHeaders(config, UserUtils.getState(user)),
                new SimpleHttpRequestListener() {

                    @Override
                    public void onResult(String response) throws JSONException {
                        parseOrderInfoJson(response);
                    }

                    @Override
                    public void onError(ApiError apiError) {
                        SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_ORDER_FAILED, apiError);
                    }
                });
    }

    private void parseOrderInfoJson(String response)
            throws JSONException {
        JSONObject data = new JSONObject(response);

        int code = data.optInt(Constant.HYKB_KEY_RESPONSE_CODE);
        String msg = data.optString(Constant.HYKB_KEY_RESPONSE_MSG);

        JSONObject dataJson = data.optJSONObject(Constant.HYKB_KEY_RESPONSE_DATA);

        if (code == Constant.HYKB_CODE_SUCCESS) {
            OrderInfo config = new OrderInfo().parseBean(dataJson);
            SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_ORDER, config);
        } else if (code == Constant.HYKB_CODE_PAY_MAINTENANCE) {
            String maintenanceContent = dataJson.optString(
                    Constant.HYKB_KEY_RESPONSE_PAY_MAINTENANCE);
            ApiError apiError = new ApiError(code, maintenanceContent);
            SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_ORDER_FAILED, apiError);
        } else if (code == Constant.HYKB_CODE_PAY_LIMIT) {
            PayLimit payLimit = new PayLimit().parseBean(dataJson);
            SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_LIMIT, payLimit);
        } else {
            ApiError apiError = new ApiError(code, msg);
            SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_ORDER_FAILED, apiError);
        }
    }

    @Override
    public void orderQuery(String orderId) {
        final Map<String, Object> param = new HashMap<>();
        param.put(Constant.HYKB_KEY_GAME_ID, SdkConfiguration.getGameId());
        param.put(Constant.HYKB_KEY_PAY_ORDER, orderId);

        InternalUser user = LoginManager.getInstance().getInternalUser();
        IHttpManager httpManager = GlobalManager.getInstance().getHttpManager();
        EnvConfig config = ApiManager.getInstance().getYuanChuangApiEnvConfig();

        httpManager.requestPost(BASE_ORDER_QUERY_URL, param,
                ApiManager.getInstance().getAuthHeaders(config, UserUtils.getState(user)),
                new SimpleHttpRequestListener() {

                    @Override
                    public void onResult(String response) throws JSONException {
                        JSONObject data = new JSONObject(response);
                        int code = data.optInt(Constant.HYKB_KEY_RESPONSE_CODE);
                        String msg = data.optString(Constant.HYKB_KEY_RESPONSE_MSG);
                        ApiError error = new ApiError(code, msg);
                        SubjectBus.get().postValue(Constant.HYKB_EVENT_PAY_ORDER_QUERY, error);
                    }

                    @Override
                    public void onError(ApiError apiError) {

                    }
                });
    }

    @Override
    public void payReport(String orderId, String content) {
        final Map<String, Object> param = new HashMap<>();
        param.put(Constant.HYKB_KEY_GAME_ID, SdkConfiguration.getGameId());
        param.put(Constant.HYKB_KEY_PAY_ORDER, orderId);
        param.put(Constant.HYKB_KEY_CONTENT, content);
        param.put(Constant.HYKB_KEY_VERSION, PayConstant.HYKB_PAY_VERSION);

        InternalUser user = LoginManager.getInstance().getInternalUser();
        IHttpManager httpManager = GlobalManager.getInstance().getHttpManager();
        EnvConfig config = ApiManager.getInstance().getYuanChuangApiEnvConfig();

        httpManager.requestPost(BASE_PAY_NOTIFY_URL, param,
                ApiManager.getInstance().getAuthHeaders(config, UserUtils.getState(user)),
                new DefaultHttpRequestListener());
    }

    @Override
    public void notifyGoods(String cpOrderId, String money, String goodsName) {
        final Map<String, Object> param = new HashMap<>();
        param.put(Constant.HYKB_KEY_PAY_GAME_ORDER, cpOrderId);
        param.put(Constant.HYKB_KEY_PAY_MONEY, money);
        param.put(Constant.HYKB_KEY_PAY_GOODS_NAME, goodsName);
        param.put(Constant.HYKB_KEY_GAME_ID, SdkConfiguration.getGameId());
        param.put(Constant.HYKB_KEY_VERSION, PayConstant.HYKB_PAY_VERSION);
        param.put(Constant.HYKB_KEY_TIME_STAMP, DateUtils.getCurrentTime());

        InternalUser user = LoginManager.getInstance().getInternalUser();
        IHttpManager httpManager = GlobalManager.getInstance().getHttpManager();
        EnvConfig config = ApiManager.getInstance().getYuanChuangApiEnvConfig();

        httpManager.requestPost(BASE_NOTIFY_GOODS_URL, param,
                ApiManager.getInstance().getAuthHeaders(config, UserUtils.getState(user)),
                new DefaultHttpRequestListener());
    }
}
